<?php
session_start();

// 修正 fun.ajax.php 和 config.php 的路径
include $_SERVER['DOCUMENT_ROOT'] . '/fun.ajax.php';

// $conf 和 $Data 变量现在应该由 fun.ajax.php 加载后可用

/**
 * 将配置写回文件
 * (此函数在 dashboard.php 中也有定义，理想情况应提取到公共文件，例如 fun.ajax.php)
 */
function saveConfig($filePath, $siteConf, $linkData)
{
    $phpCode = "<?php\n\n";
    $phpCode .= "\$conf = " . preg_replace(['/^array \(/', '/\)$/'], ['[', ']'], var_export($siteConf, true)) . ";\n\n";
    $dataExport = var_export($linkData, true);
    $dataExport = preg_replace('/^array \(/', '[', $dataExport);
    $dataExport = preg_replace('/\)$/', ']', $dataExport);
    // 移除数字键，确保是列表形式的数组
    $dataExport = preg_replace('/\s*\d+\s*=>\s*array\s*\(/', '[', $dataExport);
    $dataExport = preg_replace('/array\s*\(/', '[', $dataExport); // 处理内嵌数组
    $dataExport = preg_replace('/\)/', ']', $dataExport); // 处理内嵌数组的闭合
    $phpCode .= "\$Data = " . $dataExport . ";\n";
    return file_put_contents($filePath, $phpCode) !== false;
}

$action = $_POST['act'] ?? $_GET['act'] ?? ''; // 兼容 GET 和 POST
header('Content-Type: application/json; charset=utf-8');
// AJAX 请求处理
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
    $response = ['status' => 'error', 'message' => '未知操作或请求错误。'];

    // 验证登录状态 (除了登录和设置token操作)
    if ($action !== 'login' && $action !== 'setLoginToken') {
        if (!isset($_SESSION['ADMINTOKEN']) || $_SESSION['ADMINTOKEN'] !== $conf['token']) {
            echo json_encode(['status' => 'error', 'message' => '会话已过期，请重新登录。']);
            exit;
        }
    }

    switch ($action) {
        case 'update_site_conf':
            $new_title = $_POST['site_title'] ?? $conf['title'];
            $new_docs = $_POST['site_docs'] ?? $conf['docs'];
            $new_token = $_POST['site_token'] ?? ''; // 注意：这里不使用 $conf['token'] 作为默认值

            $conf['title'] = htmlspecialchars($new_title);
            $conf['docs'] = htmlspecialchars($new_docs);
            $token_changed = false;
            if (!empty($new_token)) {
                $conf['token'] = password_hash($new_token, PASSWORD_DEFAULT);
                $token_changed = true;
            }

            if (saveConfig($configPath, $conf, $Data)) {
                $response = ['status' => 'success', 'message' => '网站配置更新成功！', 'data' => ['token_changed' => $token_changed]];
            } else {
                $response = ['status' => 'error', 'message' => '错误：无法保存网站配置。'];
            }
            break;

        case 'add_link':
            $new_link = [
                'title' => htmlspecialchars($_POST['link_title'] ?? '新链接'),
                'description' => htmlspecialchars($_POST['link_desc'] ?? ''),
                'url' => filter_var($_POST['link_url'] ?? '#', FILTER_SANITIZE_URL),
                'icon' => htmlspecialchars($_POST['link_icon'] ?? 'fas fa-link'),
                'clicks' => 0
            ];
            $Data[] = $new_link;
            if (saveConfig($configPath, $conf, $Data)) {
                // 获取新添加链接的索引
                $new_index = count($Data) - 1;
                $response = ['status' => 'success', 'message' => '链接添加成功！', 'data' => ['new_link' => $new_link, 'new_index' => $new_index]];
            } else {
                $response = ['status' => 'error', 'message' => '错误：无法添加链接。'];
            }
            break;

        case 'edit_link':
            $index = isset($_POST['link_index']) ? intval($_POST['link_index']) : -1;
            if ($index >= 0 && isset($Data[$index])) {
                // 保留原有的clicks值，只更新其他字段
                $originalClicks = $Data[$index]['clicks'] ?? 0;
                $Data[$index]['title'] = htmlspecialchars($_POST['link_title'] ?? $Data[$index]['title']);
                $Data[$index]['description'] = htmlspecialchars($_POST['link_desc'] ?? $Data[$index]['description']);
                $Data[$index]['url'] = filter_var($_POST['link_url'] ?? $Data[$index]['url'], FILTER_SANITIZE_URL);
                $Data[$index]['icon'] = htmlspecialchars($_POST['link_icon'] ?? $Data[$index]['icon']);
                $Data[$index]['clicks'] = $originalClicks; // 确保clicks值不被覆盖

                if (saveConfig($configPath, $conf, $Data)) {
                    $response = ['status' => 'success', 'message' => '链接编辑成功！', 'data' => ['edited_link' => $Data[$index], 'index' => $index]];
                } else {
                    $response = ['status' => 'error', 'message' => '错误：无法编辑链接。'];
                }
            } else {
                $response = ['status' => 'error', 'message' => '错误：无效的链接索引。'];
            }
            break;

        case 'delete_link':
            $index = isset($_POST['link_index']) ? intval($_POST['link_index']) : -1;
            if ($index >= 0 && isset($Data[$index])) {
                array_splice($Data, $index, 1);
                if (saveConfig($configPath, $conf, $Data)) {
                    $response = ['status' => 'success', 'message' => '链接删除成功！', 'data' => ['deleted_index' => $index]];
                } else {
                    $response = ['status' => 'error', 'message' => '错误：无法删除链接。'];
                }
            } else {
                $response = ['status' => 'error', 'message' => '错误：无效的链接索引。'];
            }
            break;
    }
    echo json_encode($response);
    exit;
}
// 非AJAX请求处理 (主要用于登录、设置token、登出)
switch ($_POST['act'] ?? $_GET['act'] ?? '') {
    case 'setLoginToken':
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['token'])) {
            $newToken = trim($_POST['token']);
            $confirmToken = trim($_POST['confirm_token'] ?? '');

            // 验证两次输入的密钥是否一致
            if ($newToken !== $confirmToken) {
                $_SESSION['message'] = '两次输入的密钥不一致，请重新输入。';
            } elseif (empty($conf['token']) && !empty($newToken)) {
                // 对密钥进行哈希处理以提高安全性
                $conf['token'] = password_hash($newToken, PASSWORD_DEFAULT);
                if (saveConfig($configPath, $conf, $Data)) {
                    $_SESSION['message'] = '管理密钥设置成功！请使用新密钥登录。';
                } else {
                    $_SESSION['message'] = '错误：无法保存密钥。';
                }
            } else {
                $_SESSION['message'] = '密钥已存在或新密钥为空。';
            }
        } else {
            $_SESSION['message'] = '无效的请求。';
        }
        header('Location: index.php');
        exit;
    case 'login':
        if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['token'])) {
            $inputToken = addslashes($_POST['token']);
            if (isset($conf['token']) && password_verify($inputToken, $conf['token'])) {
                $_SESSION['ADMINTOKEN'] = $conf['token'];
                $_SESSION['message'] = '登录成功！';
                header('Location: dashboard.php');
                exit;
            } else {
                $_SESSION['message'] = '密钥错误。';
            }
        } else {
            $_SESSION['message'] = '请输入密钥。';
        }
        header('Location: index.php');
        exit;

    case 'logout':
        session_destroy();
        header('Location: index.php?message=已安全退出');
        exit;

    default:
        // 如果没有匹配的action，且不是AJAX请求，可以重定向或显示错误
        if (empty($_SERVER['HTTP_X_REQUESTED_WITH'])) {
            header('Location: index.php?message=无效的操作');
            exit;
        }
        // 对于未匹配的AJAX请求，上面已经有默认的JSON错误响应
        break;
}
